{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "#from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz\n",
      "Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz\n",
      "Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz\n",
      "Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(55000, 784)\n",
      "(10000, 784)\n",
      "(55000, 10)\n",
      "(10000, 10)\n"
     ]
    }
   ],
   "source": [
    "print(mnist.train.images.shape)\n",
    "print(mnist.test.images.shape)\n",
    "print(mnist.train.labels.shape)\n",
    "print(mnist.test.labels.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create the model\n",
    "#input layer\n",
    "W0 = tf.Variable(tf.truncated_normal([784, 100], stddev=0.01))\n",
    "b0 = tf.Variable(tf.zeros([100]))\n",
    "logit = tf.matmul(x, W0) + b0\n",
    "b_logit = tf.layers.batch_normalization(inputs=logit)\n",
    "y_input = tf.nn.elu(b_logit) \n",
    "y0 = tf.layers.dropout(rate=0.3, inputs=y_input)\n",
    "    \n",
    "#hidden layer\n",
    "W1 = tf.Variable(tf.truncated_normal([100, 100], stddev=0.01))\n",
    "b1 = tf.Variable(tf.zeros([100]))\n",
    "logit2 = tf.matmul(y0, W1) + b1\n",
    "b_logit2 = tf.layers.batch_normalization(inputs=logit2)\n",
    "y1 = tf.nn.elu(b_logit2)\n",
    "y1 = tf.layers.dropout(rate=0.3, inputs=y1)\n",
    "\n",
    "#hidden layer\n",
    "W3 = tf.Variable(tf.truncated_normal([100, 100], stddev=0.01))\n",
    "b3 = tf.Variable(tf.zeros([100]))\n",
    "logit3 = tf.matmul(y1, W3) + b3\n",
    "b_logit3 = tf.layers.batch_normalization(inputs=logit3)\n",
    "y3 = tf.nn.elu(b_logit3)\n",
    "y3 = tf.layers.dropout(rate=0.3, inputs=y3)\n",
    "\n",
    "#hidden layer\n",
    "W4 = tf.Variable(tf.truncated_normal([100, 100], stddev=0.01))\n",
    "b4 = tf.Variable(tf.zeros([100]))\n",
    "logit4 = tf.matmul(y3, W4) + b4\n",
    "b_logit4 = tf.layers.batch_normalization(inputs=logit4)\n",
    "y4 = tf.nn.elu(b_logit4)\n",
    "y4 = tf.layers.dropout(rate=0.3, inputs=y4)\n",
    "\n",
    "\n",
    "#out layer\n",
    "W2 = tf.Variable(tf.truncated_normal([100, 10], stddev=0.01))\n",
    "b2 = tf.Variable(tf.zeros([10]))\n",
    "y2 = tf.matmul(y4, W2) + b2\n",
    "y_out = tf.nn.softmax(y2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "#cross_entropy = tf.reduce_mean(\n",
    "#    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_out)\n",
    "#)\n",
    "\n",
    "cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_out+0.000000001), reduction_indices=[1]))\n",
    "#cross_entropy = -tf.reduce_sum(y_ * tf.log(y_out+0.00001))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "train_step = tf.train.AdamOptimizer(learning_rate=0.01).minimize(cross_entropy)\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "train cross_entropy: 2.30165\n",
      "test_accuracy: 0.1135\n",
      "train cross_entropy: 0.0364787\n",
      "test_accuracy: 0.9684\n",
      "train cross_entropy: 0.00653127\n",
      "test_accuracy: 0.979\n",
      "train cross_entropy: 0.0056387\n",
      "test_accuracy: 0.9767\n",
      "train cross_entropy: 0.0107077\n",
      "test_accuracy: 0.9773\n",
      "train cross_entropy: 0.00202805\n",
      "test_accuracy: 0.9768\n",
      "train cross_entropy: 0.0019066\n",
      "test_accuracy: 0.9766\n",
      "train cross_entropy: 0.00113897\n",
      "test_accuracy: 0.9779\n",
      "train cross_entropy: 0.000403592\n",
      "test_accuracy: 0.9783\n",
      "train cross_entropy: 0.000312488\n",
      "test_accuracy: 0.9802\n",
      "train cross_entropy: 0.000439302\n",
      "test_accuracy: 0.9788\n",
      "train cross_entropy: 0.00240458\n",
      "test_accuracy: 0.9798\n",
      "train cross_entropy: 0.000107677\n",
      "test_accuracy: 0.981\n",
      "train cross_entropy: 0.000256994\n",
      "test_accuracy: 0.9786\n",
      "train cross_entropy: 0.00459036\n",
      "test_accuracy: 0.9779\n",
      "train cross_entropy: 2.23134e-05\n",
      "test_accuracy: 0.9821\n",
      "train cross_entropy: 0.000267899\n",
      "test_accuracy: 0.9805\n",
      "train cross_entropy: 0.000794552\n",
      "test_accuracy: 0.9803\n",
      "train cross_entropy: 0.010434\n",
      "test_accuracy: 0.9774\n",
      "train cross_entropy: 0.00015176\n",
      "test_accuracy: 0.9813\n",
      "train cross_entropy: 0.000505747\n",
      "test_accuracy: 0.9783\n",
      "train cross_entropy: 0.0302729\n",
      "test_accuracy: 0.9747\n",
      "train cross_entropy: 2.38124e-06\n",
      "test_accuracy: 0.9818\n",
      "train cross_entropy: 1.33062e-06\n",
      "test_accuracy: 0.982\n",
      "train cross_entropy: 3.4007e-07\n",
      "test_accuracy: 0.9821\n",
      "train cross_entropy: 3.39435e-07\n",
      "test_accuracy: 0.9821\n",
      "train cross_entropy: 1.11105e-07\n",
      "test_accuracy: 0.982\n",
      "train cross_entropy: 2.0504e-08\n",
      "test_accuracy: 0.982\n",
      "train cross_entropy: 3.75513e-08\n",
      "test_accuracy: 0.9821\n",
      "train cross_entropy: 1.9908e-08\n",
      "test_accuracy: 0.9822\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for i in range(15000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(1000)\n",
    "    #print(batch_xs.shape, batch_ys.shape)\n",
    "    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    if i%500 == 0: \n",
    "        print(\"train cross_entropy:\", sess.run(cross_entropy, {x: batch_xs, y_: batch_ys}))\n",
    "        #print(\"y\", sess.run(y1, {x: batch_xs, y_: batch_ys}))\n",
    "        correct_prediction = tf.equal(tf.argmax(y_out, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(\"test_accuracy:\", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n",
    "        if sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}) >= 0.98:\n",
    "            break"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
